/**
 * Minerva core js
 * - Sets up databases.
 * - Sets up Web workers and message dispatch for them.
 * - Sets up key press event handlers.
*/

// Namespace
minerva = {};
// Event url
minerva.evurl = '/evs?format=json';

$(function() {
  console.log('minerva.js starting up ...');
  var mercury_status = $('#mercury_status');
  
  if (!window.openDatabase) { 
    // Straight bail if Web database aint' enabled
    mercury_status.html('You need an HTML5 enabled browser');
    return;
  }

  // Open database.
  // Last checked, Chrome does not support Web DB > 5MB -ph
  minerva.db = openDatabase('minerva.web.db', '1.0', 'Minerva DB', 1024*1024*5);

  if (!minerva.db) { 
    // Straight bail if we didn't get minerva db
    mercury_status.html('We were unable to open the database, bailing...');
    return;
  }

  // Create tables if necessary
  minerva.db.transaction(function(tx) { 
    // NounEvents is a replica of NounEvents in the server datastore
    // that are directed toward user.
    tx.executeSql('create table if not exists NounEvents' +
      ' (pwun integer, path varchar(255), action varchar(255), creator varchar(255), created float, type varchar(255), title varchar(255))');
    // MercuryFilters is for persisting Mercury filter configurations.
    tx.executeSql('create table if not exists MercuryFilters' +
      ' (filter_name varchar(255), root varchar(255), types varchar(255), authors varchar(255), keywords varchar(255))');
  });

  // Launch workers
  // Get current js_build number. 
  var js_build = $('#js_build').text();
  var build_ext = '.min' + js_build + '.js';
  console.log('build_ext is:', build_ext);
  // Evsync handles NounEvent syncing
  minerva.evsync_id = new Worker('/javascript/evsync' + build_ext);
  // Navclouder handles generation of tag cloud data for current location.
  minerva.navclouder_id = new Worker('/javascript/navclouder' + build_ext);
  // Filterer handles generation of results to be displayed in Mercury.
  minerva.filterer_id = new Worker('/javascript/filterer' + build_ext);

  // Setup onmessage handler for the main thread
  // This dispatches messages according to sending worker id
  // minerva.wp.onmessage = function(text, sid) {
  // console.log('Main worker pool got message:', text, sid);
  // First see if this is an ERROR message
  // if (text.indexOf('ERROR') == 0) {
  //   console.log('Error from worker!', sid, text)
  //   return;
  // }

  minerva.evsync_id.onmessage = function(event) { 
    var data = event.data;
    if (data.indexOf('ERROR') == 0) {
      console.log('Error from evsync worker!', data);
      return;
    }
    // Message from evsync, display in jGrowl
    $.jGrowl(data);
  };
   
  minerva.navclouder_id.onmessage = function(event) { 
    var data = event.data;
    if (data.indexOf('ERROR') == 0) { 
      console.log('Error from navclouder worker!', data);
      return;
    }
    // Message from navclouder, display in TagCloud
    var result = JSON.parse(data);
    var parent_path = result[0];
    var cloud_data = result[1];
    var tags = cloud_data[0];
    var pathmap = cloud_data[1];

    var tc = TagCloud.create();
    for (var tagname in tags) {
      tc.add(tagname, tags[tagname], pathmap[tagname]);
    }
    tc.loadEffector('CountSize').base(20).range(10);
    tc.setup('navcloud');
  };

  minerva.filterer_id.onmessage = function(event) { 
    var data = event.data;
    if (data.indexOf('ERROR') == 0) {
      console.log('Error from filterer worker!', data);
      return;
    }
    // Results message from filterer, display in Mercury
    // We assume that Mercury has been invoked already.
    console.log('Got filter results:', data);
    $('.mercResults').html(data);
  };

  // Setup keydown trigger for evsync start
  $(document).bind('keydown', 'Ctrl+e', function(){
    minerva.evsync_id.postMessage(minerva.evurl);
    });

  // Setup keydown trigger for Mercury overlay invocation
  var invokeMercuryOverlay = function() {
    $.mercury_prompt(function(filter_params) {
        minerva.filterer_id.postMessage(
            JSON.stringify(filter_params));
        });
    };

  var ctrl_k = 'Ctrl+k';
  $('<span/>')
      .html(ctrl_k)
      .css({'padding-left': '10px'})
      .appendTo(mercury_status);

  $(document).bind('keydown', ctrl_k, invokeMercuryOverlay);
  mercury_status.click(invokeMercuryOverlay);

  // Send message to navclouder to build cloud data for current path.
  console.log('using path', location.pathname);
  minerva.navclouder_id.postMessage(location.pathname);
  });
